<script setup lang="ts">
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus';
import { onMounted, reactive, ref, nextTick } from 'vue';
import { Search, EditPen, User, Setting } from '@element-plus/icons-vue';
import { useRoleStore } from '@/store';
import { UserAPI } from '@/api';
import { httpBatch } from '@/util/http';

const formLabelWidth = '70px';
const tableRef = ref<any>(null);
const pagination = reactive({
    total: 0, currentPage: 1
});
const roleStore = useRoleStore();
const searchModel = reactive<HttpPayload.UserSearch>({
    user_name: "", role_id: -1, begin: 0, pageSize: 5
});

const userList = ref<Vm.User[]>([]);
const formRef = ref<FormInstance | null>(null);
//定制表单校验规则
const rules = {
    user_name: [
        { required: true, message: '*用户名不能为空', trigger: "blur" },
        { min: 2, max: 20, message: '*用户名长度2 - 20', trigger: "blur" }
    ]
};

const edit = reactive<{ isEdit: boolean, type: 0 | 1 | 2, model: HttpPayload.ConfigRole }>({
    isEdit: false,
    type: 1,
    model: { user_name: "", user_pwd: "", role_id: 0 }
});

//核心函数
const getData = async (fromPage1 = true) => {
    if (fromPage1) pagination.currentPage = 1;
    searchModel.begin = (pagination.currentPage - 1) * searchModel.pageSize;
    try {
        const { total, list } = await UserAPI.get(searchModel);
        if (total > 0 && list.length === 0) {
            pagination.currentPage = Math.ceil(total / searchModel.pageSize);
            await getData(false);
            return;
        }
        pagination.total = total;
        userList.value = list;
    } catch (e) { console.log(e); }
};

onMounted(async () => {
    try {
        // await roleStore.init();
        // await getData();
        await httpBatch([() => roleStore.init(), () => getData()]);
    } catch (e) { console.log(e) }
});
const getIndex = (rowIndex: number) => {
    return (pagination.currentPage - 1) * searchModel.pageSize + rowIndex + 1;
};

const remove = async (user: Vm.User) => {
    try {
        await ElMessageBox.confirm(
            `你确定删除"${user.user_name}"吗？`,
            "Tip",
            {
                showClose: false,
                type: 'warning',
                confirmButtonText: '确定',
                cancelButtonText: '取消',
            }
        );
        await httpBatch([() => UserAPI.remove(user.user_name), () => getData(false)], true);
        ElMessage({ message: `功能："${user.user_name}"删除成功！`, type: 'success' });

    } catch (e) { console.log(e) }
};

const resetPwd = async (user: Vm.User) => {
    try {
        await ElMessageBox.confirm(
            `你确定要重置"${user.user_name}"的密码吗？`,
            "Tip",
            {
                showClose: false,
                type: 'warning',
                confirmButtonText: '确定',
                cancelButtonText: '取消',
            }
        );
        await UserAPI.resetPwd(user.user_name);
        ElMessage({ message: `"${user.user_name}"的密码重置成功！`, type: 'success' });
    } catch (e) { console.log(e); }
};
const beginAdd = () => {
    edit.type = 1;
    //重置
    formRef.value?.resetFields();
    edit.model.user_name = "";
    edit.model.user_pwd = "";
    nextTick(() => edit.isEdit = true);
};

const beginConfigRole = (user: Vm.User) => {
    edit.type = 2;
    //重置
    formRef.value?.resetFields();
    edit.model.user_name = user.user_name;
    edit.model.user_pwd = user.user_pwd;
    edit.model.role_id = user.role_id || 0;

    nextTick(() => edit.isEdit = true);
}
const ok = async () => {
    try {
        if (edit.type === 1) {
            await formRef.value?.validate();//表单验证

            await httpBatch([
                () => {
                    return new Promise((resolve, reject) => {
                        UserAPI.validateName(edit.model.user_name)
                            .then(r => {
                                if (r === 1) {
                                    ElMessageBox.alert(`用户："${edit.model.user_name}"已存在`, "警告", { type: "error" });
                                    reject();
                                }
                                else resolve(null);
                            })
                            .catch(() => reject())
                    });
                },
                () => {
                    return new Promise((resolve, reject) => {
                        UserAPI.add(edit.model.user_name)
                            .then(() => {
                                searchModel.user_name = "";
                                searchModel.role_id = -1;
                                resolve(null);
                            })
                            .catch(() => reject())
                    });
                },
                () => getData()
            ], true);
            // const r = await UserAPI.validateName(edit.model.user_name);
            // if (r === 1) {
            //     ElMessageBox.alert(`用户："${edit.model.user_name}"已存在`, "警告", { type: "error" });
            //     return;
            // }
            // searchModel.user_name = ""
            // searchModel.role_id = -1;
            // await httpBatch([() => UserAPI.add(edit.model.user_name), () => getData()], true);
            edit.isEdit = false;
            ElMessage({ message: `用户："${edit.model.user_name}"新增成功!`, type: "success", customClass: "messageIndex" });
            //下一个时间片，让新增的数据在表格中高亮显示 
            nextTick(() => {
                let i = userList.value.findIndex(item => item.user_name === edit.model.user_name);
                tableRef.value.setCurrentRow(userList.value[i]);
            });
        }
        else {
            await UserAPI.configRole(edit.model);
            const i = userList.value.findIndex(item => item.user_name === edit.model.user_name);
            userList.value[i].role_id = edit.model.role_id === 0 ? null : edit.model.role_id;
            edit.isEdit = false;
            ElMessage({ message: `用户："${edit.model.user_name}" 角色分配成功！'`, type: 'success' });
        }
    } catch (e) { console.log(e) }
}
</script>

<template>
    <el-container>
        <el-header height="50px">
            <el-form :inline="true" class="demo-form-inline">
                <el-form-item label="用户姓名:">
                    <el-input placeholder="请输入内容..." :prefix-icon="Search" v-model="searchModel.user_name"
                        @change="getData()" />
                </el-form-item>
                <el-form-item label="用户角色:">
                    <el-select v-model="searchModel.role_id" @change="getData()">
                        <el-option :value="-1" label="- 全部 -"></el-option>
                        <el-option :value="0" label="- 无角色 -"></el-option>
                        <el-option v-for="item in roleStore.roleList" :key="item.role_id" :value="item.role_id"
                            :label="item.role_name"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="success" @click="beginAdd" width=100px>＋新增</el-button>
                </el-form-item>
            </el-form>
        </el-header>
        <el-main>
            <el-table :data="userList" stripe border width=90% height=500px highlight-current-row ref="tableRef">
                <el-table-column type="index" :index="getIndex" label="#" width="100" align="center" />
                <el-table-column prop="user_name" label="用户名" width="260" align="center" />
                <el-table-column label="角色" width="260" align="center">
                    <template #default="{ row }">
                        <span v-if="row.role_id">{{ roleStore.roleList.find(item => item.role_id ===
                                row.role_id)?.role_name
                        }}</span>
                        <span v-else style="color:#ccc">- 无角色 -</span>
                    </template>
                </el-table-column>
                <el-table-column fixed="right" label="操作" align="center">
                    <template #default="{ row }">
                        <el-button type="success" size="large" :icon="EditPen" @click="resetPwd(row)">重置密码</el-button>
                        <el-button type="warning" size="large" :icon="Setting" @click="beginConfigRole(row)">分配角色
                        </el-button>
                        <el-button type="danger" size="large" :icon="User" @click="remove(row)" color="#b85d71">删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-main>
        <el-footer height="36px">
            <el-pagination background layout="prev, pager, next, jumper,->, sizes, total " :total="pagination.total"
                v-model:page-size="searchModel.pageSize" v-model:current-page="pagination.currentPage"
                :page-sizes="[3, 6, 9, 12]" @size-change="getData()" @current-change="getData(false)" />
        </el-footer>
    </el-container>

    <el-dialog :model-value="edit.isEdit" :title="edit.type === 1 ? '新增用户' : '用户角色分配'" width="30%" draggable>
        <el-form ref="formRef" :model="edit.model" :rules="rules" status-icon>
            <el-form-item prop="user_name" label="用户名" :label-width="formLabelWidth">
                <el-input v-model="edit.model.user_name" :disabled="edit.type === 2" />
            </el-form-item>
            <el-form-item label="用户角色">
                <el-select v-model="edit.model.role_id" :disabled="edit.type === 1">
                    <el-option :value="0" label="- 无角色 -"></el-option>
                    <el-option v-for="item in roleStore.roleList" :key="item.role_id" :value="item.role_id"
                        :label="item.role_name"></el-option>
                </el-select>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="edit.isEdit = false">取消</el-button>
                <el-button type="primary" @click="ok">确定</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<style scoped>
.el-container {
    margin: 5px 10px;
}

.el-header {
    height: 50px
}
</style>
